// pages/login/login.js
import {
  HttpApi
} from '../../../model/index.js'
const httpApi = new HttpApi

Page({
	/**
	 * 页面的初始数据
	 */
  data: {
    hidden: false,
    idcardCode: '',
    realName: '',
    username: '',
    password: '',
    type: 1,
    typeName: '学生登录',
  },
  onLoad() {
    //var hasLogin = wx.getStorageSync('hasLogin')
    //if(hasLogin){
    //	this.login()
    //}
  },

  login: function(e){
    var that = this;
    wx.getUserInfo({
			success: res => {
				// 可以将 res 发送给后台解码出 unionId
				// this.globalData.userInfo = res.userInfo
        console.log("getuserinfo:", res);
        var openid = wx.getStorageSync('openid');
        httpApi.login(that.data.username,that.data.password,that.data.type,res.userInfo,openid).then(res => {
          if(res.code == 200){
            wx.setStorageSync('login', "OK")
            wx.setStorageSync('userType', that.data.type)
             wx.setStorageSync('token', res.token)
          }else{
            wx.setStorageSync('login', "NO")
          }
         
          wx.navigateTo({
            url: "../../home"
          })
        })
				// 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
				// 所以此处加入 callback 以防止这种情况
				if (this.userInfoReadyCallback) {
					this.userInfoReadyCallback(res)
				}
			}
		})
    
  },
  switchChange: function (e) {
    var that = this;
    if (e.detail.value == true)
      that.setData({
        hidden: true,
        type: 2,
        typeName: '教师登录'
      });
    else
      that.setData({
        hidden: false,
        type: 1,
        typeName: '学生登录'
      });
  },
  //身份证号输入
  idcardCodeInput(e) {
    var that = this;
    that.setData({
      username: e.detail.value
    })
  },
  //姓名输入
  realNameInput(e) {
    var that = this;
    that.setData({
      password: e.detail.value
    })
  },
  //用户名输入
  userNameInput(e) {
    var that = this;
    that.setData({
      username: e.detail.value
    })
  },
  //姓名输入
  passwordInput(e) {
    var that = this;
    that.setData({
      password: e.detail.value
    })
  },

  onGotUserInfo: function (e) {
    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框						
    var that = this;
    // 可以将 res 发送给后台解码出 unionId
    // this.globalData.userInfo = res.userInfo
    var res = e.detail;
    var openid = wx.getStorageSync('openid');
    httpApi.login(that.data.username,that.data.password,that.data.type,res.userInfo,openid).then(res => {
      if(res.code == 200){
        wx.setStorageSync('login', "OK")
        wx.setStorageSync('userType', that.data.type)
         wx.setStorageSync('token', res.token)
      }else{
        wx.setStorageSync('login', "NO")
      }
     
      wx.navigateTo({
        url: "../../home"
      })
    })

    // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
    // 所以此处加入 callback 以防止这种情况
    if (this.userInfoReadyCallback) {
      this.userInfoReadyCallback(res)
    }
  },
})
